#!/usr/bin/env python
#coding:utf-8
import pkg_resources
import sys
import web

import util
import common

tpls = util.tpls

web.config.debug = False

urls=(
	'/(.*)','bbs',
)

class bbs:
	def GET(self,arg):
		try:
			ip = web.ctx.environ['HTTP_X_FORWARDED_FOR']
		except:
			ip = 'unknown'
		curpage = 1
		try:
			method,arg = arg.split('/',1)
			if method == 'list':
				cat,curpage = arg.split('/')
			elif method == 'thread':
				tid,curpage = arg.split('/')
		except Exception as what:
			method = 'list'
			cat = 'all'
			curpage = '1'
		uid = web.cookies().get('uid')
		c = common.getdb().cursor()
		if uid:
			c.execute('select nickname from ac_upers where uid=%s',(uid,))
			displayname = c.fetchone()[0].decode('utf-8')
		else:
			displayname = ip
		try:
			if method == 'list':
				curpage = int(curpage)
				c.execute('''select tid,clicks,replys,title,ifnull(nickname,'ip party'),
					lastreply + INTERVAL 4 HOUR, uid
					from acbbs_threads left join ac_upers using (uid)
					order by lastreply desc limit %s,%s''',
					((curpage-1)*common.BBS_LISTSIZE,common.BBS_LISTSIZE) )
				thds = []
				for x in c.fetchall():
					thds.append( [ x[0],x[1],x[2],x[3].decode('utf-8'),x[4].decode('utf-8'),x[5],x[6] ] )
				c.execute('select count(*) from acbbs_threads')
				curpage,threads,pages,navs,prevpage,nextpage,lastpage = util.generate_navs(int(curpage),c.fetchone()[0],common.BBS_LISTSIZE)
		
				c.execute('select count(*) from acbbs_posts')
				posts = c.fetchone()[0]
		
				c.execute('select count(*) from ac_upers')
				users = c.fetchone()[0]
		

				html = 	tpls.get_template('bbslist.html').render(cat=cat,curpage=curpage,navs=navs,prevpage=prevpage,nextpage=nextpage,lastpage=lastpage,threads=threads,posts=posts,users=users,displayname=displayname,thds=thds,uid=uid)
			elif method == 'thread':
				tid = int(tid)
				c.execute('update acbbs_threads set clicks=clicks+1 where tid=%s',(tid,))
				curpage = int(curpage)

				c.execute('select title from acbbs_threads where tid=%s',(tid,))
				title = c.fetchone()[0].decode('utf-8')
			
				c.execute('select count(*) from acbbs_posts where tid=%s',(tid,))
				total = c.fetchone()[0]
				curpage,posts,pages,navs,prevpage,nextpage,lastpage = util.generate_navs(int(curpage),total,common.BBS_THREADSIZE)

				c.execute('''select pid,uid,ifnull(nickname,ip),content,pubdate + INTERVAL 4 HOUR
							from acbbs_posts left join ac_upers using (uid)
							where tid=%s
							order by pubdate limit %s,%s
							''',(tid,common.BBS_THREADSIZE*(curpage-1),common.BBS_THREADSIZE))
				entries = []
				level = (curpage-1)*common.BBS_THREADSIZE+1
				for x in c.fetchall():
					entries.append( [ x[2].decode('utf-8'),x[1],x[0],
						x[3].decode('utf-8'),x[4],level ] )
					level += 1
				html = tpls.get_template('bbsthread.html').render(title=title,posts=posts,tid=tid,curpage=curpage,prevpage=prevpage,nextpage=nextpage,lastpage=lastpage,entries=entries,displayname=displayname,navs=navs,uid=uid)
		except Exception as what:
			return util.error_page(u"渲染错误:%s"%what.__str__())
		return html
	def POST(self,arg):
		i = web.input()
		try:
			ref = web.ctx.env.get('HTTP_REFERER')
		except:
			ref = '/'
		ip = web.ctx.environ['HTTP_X_FORWARDED_FOR']
		uid = web.cookies().get('uid')
		md5 = web.cookies().get('md5')
		if uid and md5:
			c = common.getdb().cursor()
			c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
			x = c.fetchone()
			if not( x and x[0]==md5 and x[1]==i.displayname.encode('utf-8') ):
				return util.error_page(u"用户验证失败")
		else:
			uid = 0
		uid = int(uid)
		c = common.getdb().cursor()
		try:
			i.content = i.content.replace('\n','<br>')
			if arg == 'post':
				lastuid = int(uid)
				c.execute('''insert into acbbs_threads (uid,title,lastreply,lastuid) 
					values	(%s,%s,NOW(),%s)''',(uid,i.title.encode('utf-8'),lastuid))
				c.execute('select last_insert_id()')
				tid = c.fetchone()[0]
				c.execute('insert into acbbs_posts (tid,uid,content,ip) values (%s,%s,%s,%s)',
					(tid,uid,i.content.encode('utf-8'),ip) )
				c.execute('select last_insert_id()')
				pid = c.fetchone()[0]
				c.execute('update acbbs_threads set pid=%s where tid=%s',(pid,tid))
			else:
				tid = int(arg)
				c.execute('insert into acbbs_posts (tid,uid,content,ip) values (%s,%s,%s,%s)',
					(tid,uid,i.content.encode('utf-8'),ip) )
				c.execute('update acbbs_threads set replys=replys+1,lastreply=NOW(),lastuid=%s where tid=%s',(uid,tid))
		except Exception as what:
			return what.__str__()
		return util.jump_page(u'发帖成功，跳转上个页面中………',ref)

app_bbs = web.application(urls, globals())

#if __name__ == '__main__':
#	web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)
#	app.run()
